<template>
  <div class="product-edit" style="width: 100%; height: 100%;">
    <!-- <el-page-header @back="goBack" content="商品编辑"></el-page-header> -->

    <el-form :model="form" :rules="formRules" label-width="100px" style="margin-top: 20px;">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品品牌" prop="brand_id">
        <el-select v-model="form.brand_id" placeholder="请选择品牌" style="width: 100%;">
          <el-option v-for="item in allBrandData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类" prop="category_id">
        <el-cascader v-model="form.category_id" :options="productCategoryData" placeholder="请选择商品分类"
          :props="optionProps" :show-all-levels="false" clearable style="width: 100%;">
        </el-cascader>
      </el-form-item>
      <el-form-item label="商品单位" prop="unit">
        <el-input v-model="form.unit" placeholder="请输入商品单位"></el-input>
      </el-form-item>
      <el-form-item label="封面图片" prop="cover_picture">
        <Upload :fileList.sync="coverArr" :accept="'image/*'" :limit="9" fileSize="10" multiple :fileType="1"
          @update:fileList="updateCoverFileList" />
      </el-form-item>
      <el-form-item label="相册图片" prop="album">
        <Upload :fileList.sync="albumArr" :accept="'image/*'" :limit="9" fileSize="10" multiple :fileType="1"
          @update:fileList="updateAlbumFileList" />
      </el-form-item>
      <el-form-item label="视频" prop="video">
        <Upload :fileList.sync="videoArr" :accept="'video/*'" :limit="9" fileSize="10" multiple :fileType="2"
          @update:fileList="updateVideoFileList" />
      </el-form-item>
      <el-form-item label="商品描述" prop="detail">
        <el-input type="textarea" :rows="4" placeholder="请输入商品描述" v-model="form.detail">
        </el-input>
      </el-form-item>
      <el-form-item label="基础价格" prop="base_price">
        <el-input type="number" placeholder="请输入基础价格" v-model="form.base_price">
        </el-input>
      </el-form-item>
      <el-form-item label="会员基础价格" prop="member_base_price">
        <el-input type="number" placeholder="请输入会员基础价格" v-model="form.member_base_price">
        </el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
          <el-option v-for="item in dicData" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- SKU编辑器 -->
      <el-form-item label="商品规格" prop="spec_info">
        <sku-editor ref="skuEditor"></sku-editor>
      </el-form-item>

      <!-- <el-form-item>
        <el-button type="primary" @click="submitForm">保存商品</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item> -->
    </el-form>
  </div>
</template>

<script>
import SkuEditor from '../components/SkuEditor.vue'
import Upload from './upload.vue'
import { getAllBrandList } from '../../brand/api/brand'
import { getProductCategoryList } from '../../productCategory/api/productCategory'
import { getProductItemDetail } from "../api/product";
import { getToken } from "@/util/auth";
export default {
  components: {
    SkuEditor,
    Upload
  },
  data () {
    const validateSpecInfo = (rule, value, callback) => {
      console.log("长度：", value.length);
      if (!value) {
        callback(new Error("请添加商品规格"));
      } else {
        callback()
      }
    };
    return {
      dicData: [{
        label: '上架',
        value: 0
      }, {
        label: '下架',
        value: 1
      }],
      productCategoryData: [],
      allBrandData: [],
      optionProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true
      },

      form: {},
      formRules: {
        name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        brand_id: [
          {
            required: true,
            message: "请选择商品品牌",
            trigger: "change"
          },
        ],
        category_id: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "change"
          },
        ],
        cover_picture: [
          {
            required: true,
            message: "请选择封面图片",
            trigger: "change"
          },
        ],
        album: [
          {
            required: true,
            message: "请选择相册图片",
            trigger: "change"
          },
        ],
        detail: [
          {
            required: true,
            message: "请输入商品详情",
            trigger: "blur",
          },
        ],
        base_price: [
          {
            required: true,
            message: "请输入基础价格",
            trigger: "blur",
          },
        ],
        member_base_price: [
          {
            required: true,
            message: "请输入会员基础价格",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择商品状态",
            trigger: "change"
          },
        ],
        spec_info: [
          {
            required: true,
            validator: validateSpecInfo,
            trigger: "change"
          },
        ],
      },
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  props: {
    currentData: Object,
  },
  computed: {
    headers () {
      // 上传图片添加请求头header
      return {
        'token': getToken() // 从本地获取token就行
      }
    },

  },
  watch: {
    // 深度监听
    currentData: {
      handler (val) {
        // console.log('编辑或查看', val);
        if (val.id) {
          this.getProductItemDetailData(val.id);
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted () {
    this.initProductCategoryData();
    this.initAllBrandData();
  },
  methods: {
    coverFileArr (file) {
      // 上传图片 显示默认图片
      return file ? [{ url: file }] : []
    },
    updateCoverFileList (val) {
      console.log('封面图片', val);
      this.form.cover_picture = val
    },
    updateAlbumFileList (val) {
      console.log('相册图片', val);
      this.form.album = val
    },
    updateVideoFileList (val) {
      console.log('视频', val);
      this.form.video = val
    },
    // 获取商品分类
    initProductCategoryData () {
      getProductCategoryList({ type: 1 }).then(
        (res) => {
          this.productCategoryData = res.data
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    // 获取所有品牌
    initAllBrandData () {
      getAllBrandList({}).then(
        (res) => {
          this.allBrandData = res.data
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    getProductItemDetailData (id) {
      getProductItemDetail({ id }).then(
        (res) => {
          let values = []
          this.form = { ...res.data }
          this.form.cover_picture = res.data.cover_picture_full // 封面
          this.form.album = res.data.album_full // 相册
          this.form.video = res.data.video_full // 视频
          // 规格信息
          const specsInfo = res.data.productSpecification.map(opt => {
            return {
              id: opt.id,
              spec_name: opt.spec_name,
              spec_value: values.push({
                id: opt.id,
                spec_name: opt.spec_name,
              })
            }
          })
          // sku信息
          const skuInfo = res.data.productSku.map(opt => {
            return {
              id: opt.id,
              spec_info: opt.spec_info,
              sku_code: opt.sku_code,
              price: opt.price,
              member_price: opt.member_price,
              buy_price: opt.buy_price,
              trade_price: opt.trade_price,
              stock: opt.stock,
              picture: opt.picture,
              status: opt.status,
            }
          })
          const skuData = {
            spec_info: specsInfo,
            sku_info: skuInfo
          }
          this.$refs.skuEditor.setSkuData(skuData)

        }
      );
    },

    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleMainImageSuccess (res, file) {
      // 这里应该是上传到服务器后返回的图片URL
      // 模拟上传成功
      console.log(res, file.raw);

      this.form.cover_picture = URL.createObjectURL(file.raw)
    },
    goBack () {
      this.$router.go(-1)
    },
    submitForm () {
      // 获取SKU数据
      const skuData = this.$refs.skuEditor.getSkuData()

      // 组装完整商品数据
      if (this.form.category_id.length > 0) {
        this.form.category_id = this.form.category_id[this.form.category_id.length - 1]
      }

      const productData = {
        ...this.form,
        ...skuData
      }

      console.log('提交的商品数据:', productData)
      return productData
      // 这里调用API保存商品
      // this.$api.saveProduct(productData).then(() => {
      //   this.$message.success('商品保存成功')
      //   this.goBack()
      // })
    },
    // 如果是编辑页面，加载商品数据
    loadProductData (productId) {
      // 模拟API调用
      // this.$api.getProduct(productId).then(response => {
      //   this.form = response.data.product
      //   this.$refs.skuEditor.setSkuData(response.data.skuData)
      // })

      // 模拟数据
      if (productId) {
        // this.form = {
        //   name: '测试商品',
        //   category_id: ['clothes', 't-shirt'],
        //   detail: '这是一个测试商品',
        //   cover_picture: ''
        // }

        const skuData = {
          spec_info: [
            {
              id: 'spec1',
              name: '颜色',
              values: [
                { id: 'color1', name: '红色' },
                { id: 'color2', name: '蓝色' }
              ]
            },
            {
              id: 'spec2',
              name: '尺寸',
              values: [
                { id: 'size1', name: 'S' },
                { id: 'size2', name: 'M' }
              ]
            }
          ],
          sku_info: [
            {
              id: 'sku1',
              specs: [
                { specId: 'spec1', valueId: 'color1' },
                { specId: 'spec2', valueId: 'size1' }
              ],
              price: 99,
              costPrice: 50,
              stock: 100,
              code: 'SKU001',
              image: ''
            },
            // 其他SKU...
          ]
        }

        this.$refs.skuEditor.setSkuData(skuData)
      }
    }
  },
  created () {
    // const productId = this.$route.params.id
    // if (productId) {
    //   this.loadProductData(productId)
    // }
  }
}
</script>